from pybtex.database import parse_file, BibliographyData, Entry
import os

def update_bib_entries(old_bib_file, new_bib_file):
    # 读取旧有的bib文件
    old_bib_data = parse_file(old_bib_file)
    # 读取新的bib文件
    new_bib_data = parse_file(new_bib_file)
    # # 使用新的bib条目信息更新旧有的bib条目
    for old_key,old_value in old_bib_data.entries.items():
        old_title_find = False
        for new_key,new_value in new_bib_data.entries.items():
            if not old_title_find and new_value.fields['title'] == old_value.fields['title']:
                # 更新旧有bib条目的字段值
                old_entry = old_bib_data.entries[old_key]
                old_entry.fields.update(new_value.fields)
                old_title_find = True
    # 保存更新后的bib文件
    with open(old_bib_file, 'w', encoding='utf-8') as f:
        f.write(old_bib_data.to_string('bibtex'))

if __name__== "__main__":
    project_folder = os.path.join(os.path.dirname(__file__),"..")
    bib_folder = os.path.join(project_folder,"bib_file")
    old_bib_file_name = "ori.bib"
    new_bib_file_name ="ori_from_dblp.bib"
    old_bib_file = os.path.join(bib_folder,'ori_bib',old_bib_file_name)
    new_bib_file = os.path.join(bib_folder,'new_bib',new_bib_file_name)
    update_bib_entries(old_bib_file, new_bib_file)
    print("Bib条目更新完成。")
